package com.jungle.common.config;

import cn.hutool.core.bean.BeanUtil;
import org.hibernate.HibernateException;
import org.hibernate.event.spi.PersistEvent;
import org.hibernate.event.spi.PersistEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.service.MagicAPIService;

import java.time.LocalDateTime;
import java.util.Map;

@Component
public class CustomPersistEventListener implements PersistEventListener {

    @Autowired
    MagicAPIService service;

    @Override
    public void onPersist(PersistEvent event) throws HibernateException {
        // 可以对保存或更新的实体对象进行修改处理
        Object entity = event.getObject();
        try {
            Object obj = BeanUtil.getFieldValue(entity, "createTime");
            if (obj != null) {
                LocalDateTime time = (LocalDateTime) obj;
                //如果是10s前新增加的数据就过一次规则系统，防止导入的数据也过系统
                if (time.isAfter(LocalDateTime.now().plusSeconds(-10))) {
                    service.invoke("/events/db/inserting/" + entity.getClass().getSimpleName(), Map.of("entity", entity));
                }
            }
        } catch (Exception e) {
            //skip
        }
    }

    @Override
    public void onPersist(PersistEvent event, Map createdAlready) throws HibernateException {
    }
}
